/**
 * Created by Will Bean on 2016/4/24.
 */
import React, {Component} from 'react'
//import fetch from 'isomorphic-fetch'
import CheckboxInput from './CheckboxInput'
import InputWithLabel from './InputWithLabel'
import TextInput from './TextInput'
import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import FileInput from './FileInput'
import ImageWithState from './ImageWithState'

var preview;

import {myAjax, ROOTURL} from '../publicAPI/publicAPI'

import style from './addStore.css'

class PrototypeServiceEditor extends Component {
    constructor() {
        super();
        this.state = {
            name: "",
            dname: "",
            cost0: 0,
            referencePrice: '',
            duration: 0,
            workload: 0,
            dd: true,//提交或获取时取反
            description: "",
            previewImgFiles: [],
            previewImgUrl: [],
            hasBeenMounted: false,  //判断是否已经加载
            delete: false,
            imgHash: [],
            icon: '',
            iconFile : null,
            iconPreview: '',
            iconHasChanged : false
        };
        this.handleImgUpload.bind(this);
    }

    componentWillMount() {
        preview = false;
        if(this.props.params.preview && this.props.params.preview == 'Preview'){
            preview = true;
        }else if(this.props.params.preview){
            location.href = '/PrototypeServiceM'
        }
        console.log("将安装", this.props.params.id);

        if (this.props.params.id != "undefine") {
            //    根据参数获取数据

            if (!this.state.hasBeenMounted && this.props.params.id) {
                this.setState({hasBeenMounted: true});
                console.log('set finished');
                this.handleGetInfo();
            }
        }
    }

    componentDidMount() {
    }

    handleGetInfo() {
        var url = ROOTURL + 'serv/prototype/instance.api?id=' + this.props.params.id;
        var _this = this;
        fetch(url, {
            method: "Get"
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    console.log(data);
                    _this.setState({
                        id: data.id,
                        name : data.name,
                        cost0 : data.cost0,
                        dname : data.dname,
                        description : data.meta.description,
                        workload : data.workload,
                        duration : this.changeToMin.bind(this)(data.duration),
                        imgHash : data.meta.hashed,
                        referencePrice : data.meta.referencePrice,
                        dd : !data.dd,
                        icon : data.meta.icon
                    });

                    fetch(ROOTURL + 'serv/shop/search.api?id=' + _this.props.params.id, {
                        method: 'post',
                        body: JSON.stringify({
                            "where": {"shopId": [["eq", this.props.params.id]]},
                            "order": [["id","asc"]]
                        })
                    }).then(res=> {
                        if (res.ok) {
                            res.json().then(data => {
                                console.log(data)
                                _this.setState({
                                    serviceList: data
                                });
                            })
                        }
                    })
                    console.log(_this.state)
                })
            }
        });


    }

    changeToMs(min){
        return parseInt(min*60000)
    }

    changeToMin(ms){
        return parseInt(ms/60000)
    }


    handleImgUpload(files) {
        var fileUrl = [];
        var _this = this;
        files.map(file=> {
            var freader = new FileReader();
            freader.readAsDataURL(file);
            freader.onload = function (e) {
                fileUrl.push({src: e.target.result});

                //因异步操作存在多次渲染，待修改
                _this.setState(Object.assign({}, this.state, {
                    previewImgFiles: files,
                    previewImgUrl: fileUrl
                }));
            };

        });

    }

    handleIconUpload(files) {
        var _this = this;
        this.setState({iconHasChanged:true});
        files.map(file=> {
            var freader = new FileReader();
            freader.readAsDataURL(file);
            freader.onload = function (e) {
                _this.setState(Object.assign({}, this.state, {
                    iconPreview: e.target.result,
                    iconFile : file
                }));
            };

        });

    }

    createStore() {
        var meta = {
            description: this.state.description,
            hashed: this.state.imgHash,
            icon: this.state.icon,
            referencePrice: this.state.referencePrice
        };
        var data = {
            dname: this.state.dname,
            name: this.state.name,
            cost0 : parseFloat(this.state.cost0),
            duration: this.changeToMs.bind(this)(this.state.duration),
            dd: !this.state.dd,
            workload : parseFloat(this.state.workload),
            meta: meta
        };
        var _this = this;
        console.log(data)
        var url;
        if (this.props.params.id) {
            url = ROOTURL + 'serv/prototype/instance.api?id=' + this.props.params.id;
            data.id = this.props.params.id
        } else {
            url = ROOTURL + 'serv/prototype/instance.api'
        }
        fetch(url, {
            method: 'POST',
            body: JSON.stringify(data)
        }).then(function (res) {
            if (res.ok) {
                console.log('保存成功');
                alert('保存成功');
                location.href = '/PrototypeServiceM'
            } else {
                console.log(res.status)
            }
        }).catch(function (error) {
            console.log('Request failed', error);
        });

    }

    handleIconSave(callback){
        var _this = this;
        const imgfile_url = this.state.iconPreview;
        const imgfile = this.state.iconFile;

        if(!imgfile || !imgfile_url){
            callback();
            return;
        }
        var img = new Image();
        img.src = imgfile_url;
        const width = img.width;
        const height = img.height;
        var fd = new FormData();
        var xhr = new XMLHttpRequest();
        xhr.open("POST", ROOTURL + "asset/images/upload.api?width=" + width + "&height=" + height + "&noShrink=" + true);

        fd.append("file", imgfile);
        xhr.send(fd);
        xhr.onload = function (data) {
            var status = data.currentTarget.status;
            if (status == 200) {
                var res_hashed = JSON.parse(data.currentTarget.response).hashed;
                _this.setState({
                    icon: res_hashed
                });
                callback();
            }
            else {
                console.log('图标保存失败:'+data);
                callback();
            }
        }
    }

    handlesave() {
        var _this = this;
        const imgfile_url = this.state.previewImgUrl;
        const imgfiles = this.state.previewImgFiles;
        var j = 0;
        for (var i = 0; i < imgfiles.length; i++) {
            var img = new Image();
            img.src = imgfile_url[i].src;
            const width = img.width;
            const height = img.height;
            console.log(width, height);
            var fd = new FormData();
            var xhr = new XMLHttpRequest();
            xhr.open("POST", ROOTURL + "asset/images/upload.api?width=" + width + "&height=" + height + "&noShrink=" + true);
            var f = imgfiles[i];
            fd.append("file", f);
            xhr.send(fd);
            xhr.onload = function (data) {
                var status = data.currentTarget.status;
                if (status == 200) {
                    var imageList = _this.state.previewImgUrl;
                    var imgData = _this.state.previewImgUrl[j];
                    imageList[j] = imgData;
                    imgData.msg = '保存成功';
                    _this.setState({
                        previewImgUrl: imageList
                    });
                    j++;
                    var res = data.currentTarget.response;
                    var res_json = JSON.parse(res);
                    var res_hashed = res_json.hashed;
                    _this.setState({
                        imgHash: _this.state.imgHash.concat(res_hashed)
                    });
                    if (j == imgfiles.length) {
                        _this.handleIconSave(_this.createStore.bind(_this))
                    }
                }
                else {
                    var imageList = _this.state.previewImgUrl;
                    var imgData = _this.state.previewImgUrl[j];
                    imageList[j] = imgData;
                    imgData.msg = '保存失败';
                    _this.setState({
                        previewImgUrl: imageList
                    });
                    j++;

                    if (j == imgfiles.length) {
                        _this.handleIconSave(_this.createStore.bind(_this))
                    }
                }
            }
        }
        if (!imgfiles.length) {
            _this.handleIconSave(_this.createStore.bind(_this))
        }
    }

    handleStoreDelete() {
        var url = ROOTURL + 'shop/instance.api?id=' + this.props.params.id;
        this.setState({
            delete: !this.state.delete
        });
        fetch(url, {
            method: 'delete',
            // mode : 'no-cors',
            body: JSON.stringify({})
        }).then(res=> {
            if (res.ok) {
                res.json().then(data=> {
                    console.log(data);
                })
            }
        })
    }

    deleteImg(key) {
        var newFiles = this.state.imgHash;
        newFiles.splice(key, 1);
        this.setState({
            imgFiles: newFiles
        })
    }

    render() {
        return (
            <div className="right-wrap">
                <div className="wrap" style={{position:'relative'}}>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>内部标识</label>
                        <TextInput inputId="phone" placeHolder="请输入内部标识" val={this.state.name} disabled={preview}
                                   onChange={val=>this.setState({name: val})}/>
                    </div>

                    <div className={style['input_div']} id="address">
                        <label style={{width:'110px'}}>服务显示名</label>
                        <TextInput inputId="place" placeHolder="请输入服务显示名" val={this.state.dname} disabled={preview}
                                   onChange={val=>this.setState({dname: val})}/>
                    </div>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>基础价格</label>
                        <TextInput inputId="place" placeHolder="请输入基础价格" val={this.state.cost0} disabled={preview}
                                   onChange={val=>this.setState({cost0: val})}/>
                    </div>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>参考价格</label>
                        <TextInput inputId="place" placeHolder="请输入参考价格" val={this.state.referencePrice} disabled={preview}
                                   onChange={val=>this.setState({referencePrice: val})}/>
                    </div>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>服务时长</label>
                        <TextInput inputId="place" placeHolder="请输入服务时长" val={this.state.duration} disabled={preview}
                                   onChange={val=>this.setState({duration: val})}/>
                    </div>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>并行工作荷载</label>
                        <TextInput inputId="place" placeHolder="请输入并行工作荷载" val={this.state.workload} disabled={preview}
                                   onChange={val=>this.setState({workload: val})}/>
                    </div>

                    <div className={style['input_div']}>
                        <label style={{width:'110px',float:'left'}}>服务类型图标</label>
                        <div style={{width:'316px',float:'left'}}>
                            <span style={{display:'inline-block'}}>
                                <img style={{maxWidth: '50px',maxHeight:'50px'}}
                                     src={!this.state.iconHasChanged && this.state.icon ?
                                      ROOTURL + 'asset/images/get.api?hashed=' + this.state.icon : this.state.iconPreview}/></span>
                            <button className={style['main_btn']} disabled={preview}
                                    style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',float:'right'} }
                                    >更换<FileInput disabled={preview}
                                type="file" noMultiple={true}
                                fileClass={style['imgUploader-btn']}
                                accept=".jpg,.png,.jpeg,.gif,.bmp"
                                onChange={(files)=>this.handleIconUpload(files)}/>
                            </button>
                        </div>
                    </div>
                    <div className={style['input_div']}>
                        <label style={{width:'110px'}}>文字描述</label>
                        <TextareaInput id="intro" val={this.state.description} disabled={preview} textareaClass={style.description}
                                       onChange={val=>this.setState( {description: val})}/>
                    </div>
                    <div className={style['checkbox_div']} style={{marginBottom:'20px'}}>
                        <CheckboxInput id="enabled" isCheck={this.state.dd}
                                       onChange={val=>this.setState({dd: val})}/>
                        <label htmlFor="enabled">启用</label>
                    </div>
                    <button id="submit" className={style['main_btn']} disabled={preview}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }
                            onClick={this.handlesave.bind(this)}>保存
                    </button>
                    {this.props.params.id ? <button id="delete" className={style['main_btn']} disabled={preview}
                                                    style={{backgroundColor: '#f2846f',border: '1px solid #d55c44'} }
                                                    onClick={()=>this.setState({delete: !this.state.delete})}>
                        删除</button> : null}
                    <button id="back" className={style['main_btn']} onClick={window.history.back.bind(this)}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }>返回
                    </button>
                </div>
                <div className="wrap">

                    <button id="upload" className={style['main_btn']} disabled={preview}
                            style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3'} }>图片选择上传 <FileInput
                        type="file" disabled={preview}
                        fileClass={style['imgUploader-btn']}
                        accept=".jpg,.png,.jpeg,.gif,.bmp"
                        onChange={(files)=>this.handleImgUpload(files)}/>
                    </button>
                    <span className={style['tips']} style={{marginLeft:"10px",display:'inline-block'}}>每次上传和删除图片后，请点击上方“保存”按钮进行保存</span>

                    <h3 className='catagory' style={{marginTop:"10px"}}><span className='cata-title'>上传图片列表</span></h3>
                    <ul id="fileList" className={style['img_list']}>
                        {this.state.previewImgUrl.length > 0 ? this.state.previewImgUrl.map((img, index)=> {
                            return <ImageWithState src={img.src} stateMsg={img.msg} id={index} key={index}/>
                        }) : null}
                    </ul>

                    <h3 className='catagory' style={{marginTop:"10px"}}><span className='cata-title'>服务图片列表</span></h3>
                    <ul id="imglist" className={style['img_list']}>
                        {this.state.imgHash.length > 0 ? this.state.imgHash.map((url, index)=> {
                            var src = ROOTURL + 'asset/images/get.api?hashed=' + url;
                            return <ImageWithState onClick={this.deleteImg.bind(this,index)} src={src} id={index} key={index}
                                                   deleteBtn={true}/>

                        }) : null}
                    </ul>
                </div>

                { this.state.delete ?
                    <div id={style.msgDialog}>
                        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p
                            id={style['msgDialog_content']}>确认删除？</p>
                            <div className={style['msgDialog_button']}>
                                <button id={style['msgDialog_yes']} onClick={this.handleStoreDelete.bind(this)}>确定
                                </button>
                                <button id={style['msgDialog_no']}
                                        onClick={()=>this.setState({delete: !this.state.delete})}>取消
                                </button>
                            </div>
                        </div>
                    </div> : null}
            </div>
        )
    }
}

export default PrototypeServiceEditor
